from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.field import Field
from server.model import set_field, query_by_field
import math

r_field = Blueprint('field', __name__)


@r_field.route('', methods=['POST'])
@api_auth.login_required
def add_field():
    """
    @@@
    #### Args:
            {
                gym_id: BIGINT(20    #球馆id
                name: String(64)    #名称
                status: TINYINT(unsigned=True)    #状态: 0:正常 1:未开放
            }
    #### Returns::
            {'code': 20000, 'message': "场地添加成功"}
            {'code': 50001, 'message': "添加场地时发生错误"}
    """

    args = request.get_json()

    field = Field()
    try:
        set_field(field, args)
        db.session.add(field)
        db.session.commit()

        user_opt.send({
            "operation": "添加场地",
            "method": "场地管理",
            "params": field.id,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "场地添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add field error:", e)

    return jsonify({'code': 50001, 'message': "添加场地时发生错误"})


@r_field.route('/<int:pid>', methods=['DELETE'])
@api_auth.login_required
def remove_field(pid):
    """
        @@@
        #### Args:
                field/id
        #### Returns::
                {'code': 20000, 'message': "场地删除成功"}
                {'code': 50001, 'message': "删除场地时发生错误"}
        """
    try:
        Field.query.filter_by(id=pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除场地",
            "method": "场地管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "场地删除成功"})
    except Exception as e:
        print("remove field error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除场地时发生错误"
        })


@r_field.route('/<int:pid>', methods=['PUT'])
@api_auth.login_required
def edit_field(pid):
    """
    @@@
    #### Args:
           field/id
    #### Returns::
            {'code': 20000, 'message': "场地修改成功"}
            {'code': 50001, 'message': "修改场地时发生错误"}
    """
    args = request.get_json()
    try:
        field = Field.query.filter_by(id=pid).first()
        set_field(field, args)

        db.session.commit()

        user_opt.send({
            "operation": "修改场地",
            "method": "场地管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "场地修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit field error:", e)

    return jsonify({'code': 50001, 'message': "修改场地时发生错误"})


@r_field.route('/<int:pid>', methods=['GET'])
@api_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           field/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in field_list],
                            }
                """
    field = Field.query.filter_by(id=pid).first()
    if not field:
        return jsonify({
            'code': 50002,
            'message': '查询场地不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': field.to_dict(),
    })

# >>>>> auto generate end <<<<<


@r_field.route('', methods=['GET'])
@api_auth.login_required
def get_fields():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in field_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        field_list = Field.query

        if query_filter:
            field_list = query_by_field(field_list, query_filter, Field)

        booked_fields_ids = {}

        if start_time and end_time:
            from server.model.booking import Booking
            booked_fields_ids = Booking.query.with_entities(Booking.field_id).filter(Booking.from_time <= start_time, Booking.to_time >= end_time)
            booked_fields_ids = {u[0] for u in booked_fields_ids}

        total = field_list.count()

        field_list = field_list.offset((page - 1) * limit).limit(limit).all()
        result = []
        for u in field_list:
            temp = u.to_dict()
            temp['booked'] = u.id in booked_fields_ids
            result.append(temp)

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': result,
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get fields error:", e)

    return jsonify({'code': 50001, 'message': "查询场地时发生错误"})


@r_field.route('/table', methods=['GET'])
@api_auth.login_required
def get_fields_table():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in field_list],
                            }
                """
    args = request.args
    gym_id = args.get('gym_id', type=int)
    select_date = args.get('date')
    print(select_date)

    try:
        from server.model.gym import Gym
        from server.model.booking import Booking
        gym = Gym.query.filter(Gym.id == gym_id).first()
        field_list = Field.query.filter(Field.gym_id == gym_id).all()
        bookings = Booking.query.filter(Booking.gym_id == gym_id, Booking.book_date == select_date).all()

        field_names = [u.name for u in field_list]

        book_dict = set()
        for booking in bookings:
            book_dict.add("%s_%s" % (booking.book_hour, booking.field_id))
        # 营业时间
        start_hour = int(gym.open_time.split(":")[0])
        end_hour = int(gym.close_time.split(":")[0])

        field_units = {}
        for hour in range(start_hour, end_hour):
            all_fields = []
            price = gym.count_price(hour, select_date)
            for field in field_list:
                temp = field.to_dict()
                temp['price'] = price
                book_key = "%s_%s" % (hour, field.id)
                if book_key in book_dict:
                    temp['booked'] = True
                all_fields.append(temp)
            field_units[hour] = all_fields

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': field_units,
            'start_hour': start_hour,
            'end_hour': end_hour,
            'field_names': field_names
        })
    except Exception as e:
        print("get fields error:", e)

    return jsonify({'code': 50001, 'message': "查询场地时发生错误"})
